'use strict'

var redis = require('redis')

var redisConn = require('../conf/redis.js')

var redisClient = redis.createClient(redisConn)

redisClient.on('error', function (error) {
  console.log(error)
})

redisClient.on('ready', function () {
  console.log('Redis server [' + redisConn.host + ':' + redisConn.db + '] Ready')
})

// redis_client.auth(redisConn.password);

exports.get = (key) => {
  var promise = new Promise((resolve, reject) => {
    if (redisClient.connected) {
      redisClient.get(key, (error, resp) => {
        if (error) {
          reject(error)
        } else {
          resolve(JSON.parse(resp))
        }
      })
    } else {
      resolve(null)
    }
  })

  return promise
}

exports.set = (key, obj) => {
  if (redisClient.connected) {
    redisClient.set(key, JSON.stringify(obj), (error, resp) => {
      if (error) {
        console.log(error)
      } else {
        
        let dt = new Date()
        var hour = dt.getHours()
        if (hour > 7) {
          dt.setHours(23, 59, 59, 999)
        } else {
          dt.setMinutes(59, 59, 999)
        }
        redisClient.expireat(key, parseInt(dt / 1000))
      }
    })
  }
}